package com.example.labyrinth;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper {
    public static void saveLabyrinth(String labyrinthString) throws SQLException, ClassNotFoundException {
        Connection dbConnection = getConnection();
        // Connection dbConnection = DriverManager.getConnection("jdbc:derby:myDatabase;create=true");

        createTableIfNotExist(dbConnection);

        String insertTableSQL = "INSERT INTO LABYRINTHS (maze) VALUES (?)";
        PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
        preparedStatement.setString(1, labyrinthString);

        preparedStatement.executeUpdate();
    }

    private static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        Connection dbConnection = DriverManager.getConnection("jdbc:derby:memory:myDatabase;create=true");
        return dbConnection;
    }

    private static void createTableIfNotExist(Connection dbConnection) throws SQLException {
        DatabaseMetaData dbmd = dbConnection.getMetaData();
        ResultSet rs = dbmd.getTables(null, "APP", "LABYRINTHS", null);
        if (!rs.next()) {
            Statement statement = dbConnection.createStatement();
            statement
                    .executeUpdate("CREATE TABLE LABYRINTHS(id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY, maze VARCHAR(1000), PRIMARY KEY(id))");
            statement.close();
        }
    }

    public static List<LabyrinthRow> getAllLabyrinhts() throws ClassNotFoundException, SQLException {
        List<LabyrinthRow> labyrinthRows = new ArrayList<>();

        Connection dbConnection = getConnection();
        Statement statement = dbConnection.createStatement();

        String sql = "SELECT id, maze FROM LABYRINTHS";
        ResultSet rs = statement.executeQuery(sql);
        while (rs.next()) {
            LabyrinthRow labyrinthRow = new LabyrinthRow();

            // Retrieve by column name
            labyrinthRow.id = rs.getInt("id");
            labyrinthRow.labyrinthString = rs.getString("maze");

            labyrinthRows.add(labyrinthRow);
        }
        rs.close();

        return labyrinthRows;
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        saveLabyrinth("abc");
    }
}
